package com.acwing.lc.part1;

import java.util.Stack;

/**
 * @author rkc
 * @date 2022/9/12 10:09
 */
public class LC32最长有效括号 {

    private Stack<Integer> stk = new Stack<>();

    public int longestValidParentheses(String s) {
        int ans = 0;
        for (int i = 0, start = -1; i < s.length(); i++) {
            if (s.charAt(i) == '(') stk.push(i);
            else {
                if (!stk.isEmpty()) {
                    stk.pop();
                    if (!stk.isEmpty()) {
                        ans = Math.max(ans, i - stk.peek());
                    } else {
                        ans = Math.max(ans, i - start);
                    }
                } else {
                    start = i;
                }
            }
        }
        return ans;
    }
}
